package com.example.crawler.controller;

import com.example.crawler.service.CrawlerService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
 * @Author hjq
 *
 * @Date 02/28/2019 16:49
 *
 * @Description //TODO  爬虫启动类
 */
@Controller
public class CrawlerController {
    @Autowired
    private CrawlerService crawlerService;

    /**
     * 跳转到主页面
     */
    @GetMapping(value = "/toIndex.do")
    public String toIndex(){
       return "/index";
    }

    /**
     * 返回给客户端下载文件
     * @param cityName
     * @param type
     * @return
     */
    @GetMapping(value = "/export")
    @ResponseBody
    public void getHSSFWorkbook(HttpServletRequest request, HttpServletResponse response, String cityName, String type){
        //excel文件名
        String fileName = cityName+"市"+initType(type)+"表"+System.currentTimeMillis()+".xls";
        //创建HSSFWorkbook
        HSSFWorkbook wb = crawlerService.initSchoolExele(cityName,type);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String initType(String name){
        switch (name){
            case "youeryuan":
                return "幼儿园";
            case "chuzhong":
                return "初中";
            case "gaozhong":
                return "高中";
            case "daxue":
                return "大学";
            case "chengrenjiaoyu":
                return "成人教育";
            case "peixunjigou":
                return "培训机构";
            default:
                return "高中";
        }
    }

    /**
     *  发送响应流的方法
     * @param response
     * @param fileName
     */
    private void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
